package com.xunshibao.tutor.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xunshibao.tutor.po.Area;

@Controller
@RequestMapping(value = "/area/*")
public class AreaController {
	@Autowired
	private AreaServiceImpl areaService;

	@RequestMapping(value = "get")
	public @ResponseBody
	List<Map<String, Object>> getArea(@RequestParam(value = "tp") Integer tp,
			@RequestParam(value = "pid", required = false) Integer parentId) {
		List<Area> areaList = null;
		switch (tp) {
		case 0:// Area.TYPE.PROVINCE.value()
			areaList = areaService.getProvinces();
			break;
		case 1:// Area.TYPE.CITY.value()
			areaList = areaService.getCities(parentId);
			break;
		case 2:// Area.TYPE.DISTINCT.value()
			areaList = areaService.getDistincts(parentId);
			break;
		}
		if(areaList == null) {
			areaList = Collections.emptyList();
		}
		return area2Map(areaList);
	}
	
	private List<Map<String, Object>> area2Map(List<Area> areaList) {
		if(areaList != null) {
			List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
			Map<String, Object> map =  null;
			Area area;
			Iterator<Area> iter = areaList.iterator();
			while(iter.hasNext()) {
				area = iter.next();
				map = new HashMap<String, Object>();
				map.put("n", area.getName());
				map.put("c", area.getCode());
				if(area.getSpe() != null) {
					map.put("s", 1);
				}
				iter.remove();
				listMap.add(map);
			}
			return listMap;
		} else {
			return Collections.emptyList();
		}
	}
}
